package com.ming.springboot.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created by mqsi on 2022/5/24 11:29
 */
@Configuration
public class SelfSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	SelfAuthenticationProvider provider;

	@Autowired
	AjaxAuthenticationEntryPoint entryPoint;

	@Autowired
	AjaxAuthenticationSuccessHandler successHandler;

	@Autowired
	AjaxAuthenticationFailureHandler failureHandler;

	@Autowired
	AjaxAccessDeniedHandler accessDeniedHandler;

	@Autowired
	SelfLogoutSuccessHandler logoutSuccessHandler;

	@Autowired
	SelfUserDetailService userDetailService;

	@Autowired
	JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

	@Bean
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 自定义缓存中登录验证的用户名、密码，此处为明文登录，默认密文
//		auth.inMemoryAuthentication().passwordEncoder(new SimplePasswordEncoder())
//				.withUser("admin").password("admin@123").roles("ADMIN");
//		auth.authenticationProvider(provider);
		auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
	}

	/**
	 * 配置自定义登录界面的请求处理
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 设置Session策略为无状态，即禁用Session
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.httpBasic().authenticationEntryPoint(entryPoint)
				.and()
				.authorizeRequests()
				.antMatchers("/**/webjars/**").permitAll()
				.antMatchers("/**/swagger-ui.html").permitAll()
				.antMatchers("/**/swagger-resources/**").permitAll()
				.antMatchers("/**/swagger-ui/**").permitAll()
				.antMatchers("/**/v2/api-docs").permitAll()
				.anyRequest().authenticated()
				//具体权限访问的过滤处理方法调用
//				.anyRequest().access("@rbacAuthorityService.hasPermission(request, authentication)")
				.and()
				.formLogin().loginPage("/login").permitAll()
//				.defaultSuccessUrl("/webapp/success.html")
				.successHandler(successHandler)
				.failureHandler(failureHandler)
				.and()
				.csrf().disable();
		//无权限的处理逻辑类加载
		http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
		http.logout().logoutSuccessHandler(logoutSuccessHandler).permitAll();
		// 设置自动登录参数及超时时间，单位为秒
		http.rememberMe().rememberMeParameter("remember-me")
				.userDetailsService(userDetailService).tokenValiditySeconds(500);

		http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
		// 禁用请求的Header缓存
		http.headers().cacheControl();
	}

}
